<?php


namespace app\superpartner\controller;

use app\common\controller\CommonService;
use think\facade\Validate;
use think\Controller;
use think\Request;
use think\Db;

class Partner extends Controller
{
    /**
     *我的合伙人列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function partnerList(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = $request->post();
        $db = Db::name('partner')
            ->alias('p')
            ->join('user_manage u', 'u.id = p.uid','LEFT')
            ->where('p.super_partner_id', $superPartnerId);
        if (!empty($requestData['nickname'])){
            $db = $db->where('u.nickname|u.xingming',$requestData['nickname']);
        }
        if (!empty($requestData['code'])){
            $db = $db->where('u.code',$requestData['code']);
        }
        if (!empty($requestData['tel'])){
            $db = $db->where('u.tel',$requestData['tel']);
        }
        if (!empty($requestData['status'])){
            $db = $db->where('p.status',$requestData['status']);
        }
        if (!empty($requestData['reg_start']) && !empty($requestData['reg_end'])){
            $db = $db->whereBetween('p.reg_time',[strtotime($requestData['reg_start']),strtotime($requestData['reg_end'])]);
        }
        if (!empty($requestData['order_type']) && !empty($requestData['sort_type'])){
            $db = $db->order($requestData['order_type'],$requestData['sort_type']);
        }else {
            $db = $db->order('p.reg_time','desc');
        }
        $date['total_num'] = $db->count();
        $data['data'] = $db
            ->field('u.headimgurl,p.id as id,p.remark,u.id as uid,u.nickname,u.xingming,u.code,u.tel,p.status as status,p.reg_time,p.rebate_percent,p.money as money')
            ->page(input('page', 1), input('limit', 20))
            ->select();
        foreach ($data['data'] as $k => $v) {
            $date['data'][$k]['id'] = $v['id'];
            $date['data'][$k]['uid'] = $v['uid'];
            $date['data'][$k]['headimgurl'] = $v['headimgurl'];
            $date['data'][$k]['xingming'] = CommonService::emoji_decode($v['nickname']) ? CommonService::emoji_decode($v['nickname']) : $v['xingming'];
            $date['data'][$k]['code'] = $v['code'];
            $date['data'][$k]['tel'] = $v['tel'];
            $date['data'][$k]['status'] = $v['status'];
            $date['data'][$k]['rebate_percent'] = $v['rebate_percent'];
            $date['data'][$k]['money'] = $v['money'];
            $date['data'][$k]['reg_time'] =    date('Y-m-d H:i:s',$data['data'][$k]['reg_time']);
            $date['data'][$k]['invite_num'] = $this->getInviteCount($v['uid']);
            $partnerOrderInfo = $this->getPartnerOrderInfo($v['id']);
            $date['data'][$k]['order_count'] = $partnerOrderInfo['count'];
            $date['data'][$k]['order_volume'] = $partnerOrderInfo['order_volume'];
            $date['data'][$k]['order_profit'] = $partnerOrderInfo['order_profit'];
        }
        return CommonService::success($date);
    }
    /**获取合伙人推广用户的订单
     *order_num 有效订单数量
     *order_volume 累计销售订单额
     *order_profit 累计利润
     * */
    public function getPartnerOrderInfo($id)
    {
        $uids = Db::name('user_manage')->where('partner_id', $id)->column('id');
        if (!empty($uids)){
            $tbOrder = Db::name('tb_order')
                ->where('uid', 'in', $uids)
                ->where('order_type', 1)
                ->where('is_weiquan', 0)
                ->where('order_status', '<>', 0)
                ->field('SUM(user_buy_price) as order_volume,SUM(partner_rebate_fee) as order_profit,count(1) as count')
                ->find();
            $jdOrder = Db::name('jd_order')
                ->where('uid', 'in', $uids)
                ->where('order_status', '<>', 0)
                ->field('SUM(user_buy_price) as order_volume,SUM(partner_rebate_fee) as order_profit,count(1) as count')
                ->find();
            $pddOrder = Db::name('pdd_order')
                ->where('uid', 'in', $uids)
                ->where('order_status', '<>', 0)
                ->field('SUM(user_buy_price) as order_volume,SUM(partner_rebate_fee) as order_profit,count(1) as count')
                ->find();
            $data['count'] = $tbOrder['count'] + $jdOrder['count'] + $pddOrder['count'];
            $data['order_volume'] = (string)($tbOrder['order_volume'] + $jdOrder['order_volume'] + $pddOrder['order_volume']);
            $data['order_profit'] = (string)($tbOrder['order_profit'] + $jdOrder['order_profit'] + $pddOrder['order_profit']);
        } else {
            $data['count'] = 0;
            $data['order_volume'] = 0;
            $data['order_profit'] = 0;
        }
        return $data;
    }
    /*获取合伙人推广人数
     *invite_num
     * */
    public function getInviteCount($id)
    {
        $data = Db::name('user_manage')
            ->where('par_id', $id)
            ->count();
        return $data;
    }
    /**
     *查询用户信息
     * tel 手机号
     */
    public function getPartner(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = $request->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $user = Db::name('user_manage')->where('tel', $requestData['tel'])->where('super_partner_id',$superPartnerId)->find();
        if (empty($user)) {
            return CommonService::error('该用户不存在或不是你的用户！');
        }
        $partnerInfo = Db::name('partner')->where('uid', $user['id'])->where('super_partner_id',$superPartnerId)->find();
        if (!empty($partnerInfo)){
            return CommonService::error(100);
        }
        $partner_max = $this->getPartnerRebatePercent($superPartnerId);
        $data['partnerRebate_max'] = $partner_max['partnerRebate_max'];
        $data['partnerRebate'] = $partnerInfo['rebate_percent'] ? $partnerInfo['rebate_percent'] : 0;
        $data['superPartnerRebate'] = $partner_max['superPartnerRebate'];
        $data['nickname'] = CommonService::emoji_decode($user['nickname']);
        $data['tel'] = $user['tel'];
        $data['code'] = $user['code'];
        $data['partner_id'] = $user['partner_id'];
        $data['id'] = isset($user['id']) ? $user['id'] : '';
        return CommonService::success($data);
    }
    /**
     *增加合伙人
     * uid 用户id
     * rebate_percent 提成比例
     */
    public function partnerAdd(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = $request->post();
        $validate = Validate::make([
            'uid|用户id' => 'require|number',
            'rebate_percent|提成比例' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $user = Db::name('user_manage')->where('id', $requestData['uid'])->where('super_partner_id',$superPartnerId)->find();
        if (empty($user)) {
            return CommonService::error('该用户不存在或不是你的用户！');
        }
        $partnerInfo = Db::name('partner')->where('uid', $user['id'])->where('super_partner_id',$superPartnerId)->find();
        if (!empty($partnerInfo)){
            return CommonService::error(100);
        }
        $data = $this->getPartnerRebatePercent($superPartnerId);
        if ($requestData['rebate_percent'] > $data['partnerRebate_max'] || $requestData['rebate_percent'] < 0){
            return CommonService::error(102);
        }
        $addSuper = Db::name('partner')->insert([
            'uid' => $requestData['uid'],
            'rebate_percent' => $requestData['rebate_percent'],
            'password' => '',
            'alipay_no' => '',
            'alipay_name' => '',
            'reg_time' => time(),
            'login_time' => '',
            'super_partner_id' => $superPartnerId,
        ]);
        if (!$addSuper){
            return CommonService::error(0);
        }
        $partnerId = Db::name('partner')->where('uid', $user['id'])->where('super_partner_id',$superPartnerId)->value('id');
        $eUser = Db::name('user_manage')->where('id', $user['id'])->update([
            'partner_id' => $partnerId,
        ]);
        if ($eUser){
            return CommonService::success([],107);
        } else {
            return CommonService::error(0);
        }
    }
    /**
     *修改合伙人比例
     *id 合伙人id
     *rebate_percent 提成比例
     *remark 备注
     */
    public function partnerEdit(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = $request->post();
        $validate = Validate::make([
            'id|合伙人id' => 'require|number',
            'rebate_percent|提成比例' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $data = $this->getPartnerRebatePercent($superPartnerId);
        if ($requestData['rebate_percent'] > $data['partnerRebate_max'] || $requestData['rebate_percent'] < 0){
            return CommonService::error(102);
        }
        $partnerId = Db::name('partner')->where('id', $requestData['id'])->where('super_partner_id',$superPartnerId)->find();
        if (!$partnerId){
            return CommonService::error(1);
        }
        $result = Db::name('partner')->where('id', $requestData['id'])->update([
            'rebate_percent' => $requestData['rebate_percent'],
            'remark' => !empty($requestData['remark']) ? $requestData['remark'] : '',
        ]);
        if ($result){
            return CommonService::success([],106);
        } else {
            return CommonService::error(0);
        }
    }
    /**
     *禁用合伙人
     *id 合伙人id
     *status 1 0 是否禁用
     *remark 备注
     *super_partner_id 超级合伙人
     *partner_id 合伙人
     *time 时间
     */
     public function partnerStutasEdit(Request $request)
     {
         $superPartnerId = $request->superPartnerId;
         $requestData = $request->post();
         $validate = Validate::make([
             'id' => 'require',
             'status|状态' => 'require|in:0,1',
         ]);
         if (!$validate->check($requestData)) {
             return CommonService::error($validate->getError());
         }
         $partner = Db::name('partner')->where('id',$requestData['id'])->where('super_partner_id',$superPartnerId)->find();
         if (empty($partner)){
             return CommonService::error(1);
         }
         if ($partner['status'] == $requestData['status']){
             if ($partner['status'] == 1){
                 return CommonService::error(104);
             }
             if ($partner['status'] == 0){
                 return CommonService::error(103);
             }
         }
         Db::startTrans();
         try {
             Db::name('partner')->where('id', $requestData['id'])->update([
                 'status' => $requestData['status'],
                 'remark' => $requestData['remark'],
             ]);
             Db::name('partner_status_log')->insert([
                 'super_partner_id' => $superPartnerId,
                 'partner_id' => $requestData['id'],
                 'status' => $requestData['status'],
                 'remark' => $requestData['remark'],
                 'time' => time()
             ]);
             Db::commit();
             return CommonService::success([], 106);
         } catch (\Exception $e) {
             Db::rollback();
             return CommonService::error(0);
         }
     }
    /**
     *禁用合伙人列表
     *superPartnerId 超级合伙人id
     *nickname 姓名
     *code 邀请码
     *tel 手机号
     *start_time end_time 时间
     */
    public function partnerStutasList(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = $request->post();
        $db = Db::name('partner_status_log')
            ->alias('l')
            ->join('partner p','p.id = l.partner_id','LEFT')
            ->join('user_manage u','u.id = p.uid','LEFT')
            ->where('l.super_partner_id',$superPartnerId);
        if (!empty($requestData['nickname'])){
            $db = $db->where('u.nickname',$requestData['nickname']);
        }
        if (!empty($requestData['code'])){
            $db = $db->where('u.code',$requestData['code']);
        }
        if (!empty($requestData['tel'])){
            $db = $db->where('u.tel',$requestData['tel']);
        }
        if (!empty($requestData['start_time']) && !empty($requestData['end_time'])){
            $db = $db->whereBetween('partner_status_log.time', [strtotime($requestData['start_time']),strtotime($requestData['end_time'])]);
        }
        if (!empty($requestData['order_type']) && !empty($requestData['sort_type'])){
            $db = $db->order($requestData['order_type'],$requestData['sort_type']);
        }else {
            $db = $db->order('l.id','desc');
        }
        $date['total_num'] = $db->count();
        $data['data'] = $db->field('u.headimgurl,u.nickname,u.tel,u.code,l.status,l.time,l.remark')
            ->page(input('page',1),input('limit',20))
            ->select();
        foreach ($data['data'] as  $k => $v){
            $date['data'][$k]['headimgurl'] = $v['headimgurl'];
            $date['data'][$k]['nickname'] = CommonService::emoji_decode($data['data'][$k]['nickname']);
            $date['data'][$k]['tel'] = $v['tel'];
            $date['data'][$k]['code'] = $v['code'];
            $date['data'][$k]['status'] = $v['status'];
            $date['data'][$k]['time'] = date('Y-m-d H:i:s',$data['data'][$k]['time']);
            $date['data'][$k]['remark'] = $v['remark'];
        }
        return CommonService::success($date);
    }
    /**
     *获取合伙人最高设置比例
     * partnerId
     */
    public function getPartnerRebatePercent($id)
    {
        $partner = Db::name('super_partner')->where('id',$id)->find();
        $data['superPartnerRebate'] = $partner['user_one_rebate_percent'];
        $data['partnerRebate_max'] = 28 - $partner['user_one_rebate_percent'];
        return $data;
    }
}